import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import useUsersStore from "@/store/useUsersStore";
const views = import.meta.glob("@/views/*.vue");
const topRoutes = ["login"];
let routes: Array<RouteRecordRaw> = Object.keys(views)
  .map((path) => {
    const name = path
      .split("/")
      .find((it) => it.includes(".vue"))
      ?.replace(".vue", "");
    if (!name) return;
    if (topRoutes.includes(name)) {
      return {
        path: `/${name}`,
        name,
        component: views[path],
      };
    }
    return {
      path: `${name}`,
      name,
      component: views[path],
    };
  })
  .filter(Boolean) as Array<RouteRecordRaw>;
const children = routes.filter((it: any) => !topRoutes.includes(it.name));
const parent = routes.filter((it: any) => topRoutes.includes(it.name));
routes = [
  ...parent,
  {
    path: "/",
    redirect: "/home",
    component: () => import("@/layout/index.vue"),
    children,
  },
  { path: "/:pathMatch(.*)*", redirect: "/404" },
];
console.log(routes);
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    return { top: 0 };
  },
});
const whiteList = ["/login"];
router.beforeEach((to, from, next) => {
  // const token = sessionStorage.getItem("token");
  const usersStore = useUsersStore();
  const token = usersStore.token;
  if (token) {
    if (whiteList.includes(to.path)) {
      next("/chat");
    } else {
      next();
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});
export default router;
